package com.gzhryc.shared_device.cdcz.code;

import com.gzhryc.common.ClassTools;
import com.gzhryc.common.DateTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.JdbcSession;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.shared_device.cdcz.code.dao.db.*;
import com.gzhryc.shared_device.cdcz.code.dao.enums.ChargeSocketEnum;
import com.gzhryc.shared_device.cdcz.code.dao.enums.ChargeSocketSlaveDeviceEnum;
import com.gzhryc.shared_device.cdcz.code.dao.enums.ChargeSocketSlotEnum;
import com.gzhryc.shared_device.cdcz.code.services.ChargeSocketSlaveDeviceService;
import com.gzhryc.shared_device.cdcz.core.CDCZConstants;
import com.gzhryc.shared_device.cdcz.core.enums.ECDCZPlugWorkState;
import com.gzhryc.shared_device.cdcz.core.protocol.v2.V2_CDCZNetworkService;
import com.gzhryc.shared_device.common.device.dao.db.DeviceUpgradeTask;
import com.gzhryc.shared_device.common.device.dao.models.UpgradeProcessInfo;
import com.gzhryc.shared_device.common.device.services.DeviceUpgradeTaskService;
import com.gzhryc.shared_device.iot.code.IIOTLogServer;
import com.gzhryc.shared_device.iot.core.IOTClient;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.cdcz.code.dao.enums.CDCZOrderEnum;
import com.gzhryc.shared_device.cdcz.code.services.ChargeSocketService;
import com.gzhryc.shared_device.cdcz.code.services.ChargeSocketSlotService;
import com.gzhryc.shared_device.cdcz.code.services.CDCZOrderService;
import com.gzhryc.shared_device.cdcz.core.ICDCZNetworkEventListener;
import com.gzhryc.shared_device.cdcz.core.ICDCZNetworkService;
import com.gzhryc.shared_device.cdcz.core.models.*;
import com.gzhryc.shared_device.cdcz.core.protocol.v1.V1_CDCZNetworkService;

import java.util.Date;

public class CDCZNetworkEventListener implements ICDCZNetworkEventListener {

    static Logger log = Logger.getLogger(CDCZNetworkEventListener.class);

    private final String jdbcKey;
    private final OperateInfo operateInfo;
    private final IIOTLogServer iotLogServer;
    private final ICDCZBusinessEventListener businessEventListener;
    private final ICDCZCacheManager cacheManager;

    public CDCZNetworkEventListener(String jdbcKey, IIOTLogServer iotLogServer,
                                    ICDCZBusinessEventListener businessEventListener,ICDCZCacheManager cacheManager,OperateInfo operateInfo){
        this.jdbcKey = jdbcKey;
        this.iotLogServer = iotLogServer;
        this.businessEventListener = businessEventListener;
        this.cacheManager = cacheManager;
        this.operateInfo = ClassTools.copy(new OperateInfo(),operateInfo);
        this.operateInfo.setOperator("充电插座网络事件监听程序");
    }

    @Override
    public boolean online(CDCZOnlineNotify onlineNotify) {
        MultiDBTools.setJdbcKey(jdbcKey);
        try {
            boolean toSave = true;
            ChargeSocket chargeSocket = cacheManager.getChargeSocket(onlineNotify.getDeviceSn());
            if(chargeSocket == null){
                chargeSocket = ChargeSocketService.self().getByDeviceSn(onlineNotify.getDeviceSn());
                if(chargeSocket != null) {
                    ChargeSocketService.self().online(chargeSocket,onlineNotify.getVersion(),onlineNotify.getIccid(),onlineNotify.getRssi());
                    chargeSocket.setVersionNumber(onlineNotify.getVersion());
                    chargeSocket.setIccid(onlineNotify.getIccid());
                    chargeSocket.setRssi(onlineNotify.getRssi());
                    chargeSocket.setState(ChargeSocketEnum.State.Online.index());
                    chargeSocket.setHeartbeatData(new Date());
                    cacheManager.saveChargeSocket(chargeSocket);
                    toSave = false;
                }
            }
            if (chargeSocket != null) {
                if(toSave){
                    ChargeSocketService.self().online(chargeSocket,onlineNotify.getVersion(),onlineNotify.getIccid(),onlineNotify.getRssi());
                    chargeSocket.setVersionNumber(onlineNotify.getVersion());
                    chargeSocket.setIccid(onlineNotify.getIccid());
                    chargeSocket.setRssi(onlineNotify.getRssi());
                    chargeSocket.setState(ChargeSocketEnum.State.Online.index());
                    chargeSocket.setHeartbeatData(new Date());
                    cacheManager.saveChargeSocket(chargeSocket);
                }
                DeviceUpgradeTaskService.self().executeCheck(chargeSocket.getDeviceSn(),onlineNotify.getVersion());
                return true;
            }else {
                log.error("设备上线通知，未找到设备信息，报文：{{0:json}}",onlineNotify);
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }finally {
            JdbcSession.clear();
            MultiDBTools.removeJdbcKey();
        }
        return false;
    }

    @Override
    public void heartbeat(IOTClient iotClient,CDCZHeartbeatNotify heartbeatNotify) {
        MultiDBTools.setJdbcKey(jdbcKey);
        try {
            boolean toSave = true;
            ChargeSocket chargeSocket = cacheManager.getChargeSocket(heartbeatNotify.getDeviceSn());
            if(chargeSocket == null){
                chargeSocket = ChargeSocketService.self().getByDeviceSn(heartbeatNotify.getDeviceSn());
                if(chargeSocket != null) {
                    ChargeSocketService.self().heartbeat(chargeSocket,heartbeatNotify.getRssi(), heartbeatNotify.getMcuTemperature());
                    chargeSocket.setRssi(heartbeatNotify.getRssi());
                    chargeSocket.setMcuTemperature(heartbeatNotify.getMcuTemperature());
                    chargeSocket.setState(ChargeSocketEnum.State.Online.index());
                    chargeSocket.setHeartbeatData(new Date());
                    cacheManager.saveChargeSocket(chargeSocket);
                    toSave = false;
                }
            }
            if(chargeSocket != null) {
                if(toSave){
                    ChargeSocketService.self().heartbeat(chargeSocket,heartbeatNotify.getRssi(), heartbeatNotify.getMcuTemperature());
                    chargeSocket.setRssi(heartbeatNotify.getRssi());
                    chargeSocket.setMcuTemperature(heartbeatNotify.getMcuTemperature());
                    chargeSocket.setState(ChargeSocketEnum.State.Online.index());
                    chargeSocket.setHeartbeatData(new Date());
                    cacheManager.saveChargeSocket(chargeSocket);
                }

                ICDCZNetworkService networkService = getNetworkService(iotClient);

                for(Integer slotNum = 1; slotNum <= chargeSocket.getSlotTotal(); slotNum++) {
                    CDCZPlugInfo plugInfo = null;
                    if (heartbeatNotify.getPlugInfoList() != null && heartbeatNotify.getPlugInfoList().size() > 0) {
                        for (CDCZPlugInfo item : heartbeatNotify.getPlugInfoList()) {
                            if (item.getSlotNum().equals(slotNum)) {
                                plugInfo = item;
                                break;
                            }
                        }
                    }

                    toSave = true;
                    ChargeSocketSlot socketSlot = cacheManager.getChargeSocketSlot(heartbeatNotify.getDeviceSn(), slotNum);
                    if (socketSlot == null) {
                        socketSlot = ChargeSocketSlotService.self().getJoinByKeys(heartbeatNotify.getDeviceSn(), slotNum);
                        if (socketSlot != null) {
                            if (plugInfo != null) {
                                ChargeSocketSlotService.self().updateInfo(socketSlot,
                                        plugInfo.getWorkState(), plugInfo.getOverloadState(), plugInfo.getPowerState(), plugInfo.getTemperatureState());
                                socketSlot.setOverloadState(plugInfo.getOverloadState());
                                socketSlot.setPowerState(plugInfo.getPowerState());
                                socketSlot.setTemperatureState(plugInfo.getTemperatureState());
                                if (ECDCZPlugWorkState.Charge.index().equals(plugInfo.getWorkState())) {
                                    socketSlot.setState(ChargeSocketSlotEnum.State.Working.index());
                                } else {
                                    socketSlot.setState(ChargeSocketSlotEnum.State.Free.index());
                                }
                            } else {
                                if (ChargeSocketSlotEnum.State.Working.index().equals(socketSlot.getState())) {
                                    log.error("{{0}}设备{{1}}卡槽状态为工作中，但心跳无该卡槽，修改卡槽为空闲",socketSlot.getDeviceSn(),socketSlot.getSlotNum());
                                    ChargeSocketSlotService.self().toFree(socketSlot.getDeviceSn(), socketSlot.getSlotNum());
                                }
                                socketSlot.setState(ChargeSocketSlotEnum.State.Free.index());
                            }
                            cacheManager.saveChargeSocketSlot(socketSlot);
                            toSave = false;
                        }
                    }

                    if (socketSlot != null) {
                        if (plugInfo != null) {
                            if(toSave) {
                                if (ChargeSocketSlotService.self().updateInfo(socketSlot,
                                        plugInfo.getWorkState(), plugInfo.getOverloadState(), plugInfo.getPowerState(), plugInfo.getTemperatureState())) {
                                    socketSlot.setOverloadState(plugInfo.getOverloadState());
                                    socketSlot.setPowerState(plugInfo.getPowerState());
                                    socketSlot.setTemperatureState(plugInfo.getTemperatureState());
                                    if (ECDCZPlugWorkState.Charge.index().equals(plugInfo.getWorkState())) {
                                        socketSlot.setState(ChargeSocketSlotEnum.State.Working.index());
                                    } else {
                                        socketSlot.setState(ChargeSocketSlotEnum.State.Free.index());
                                    }
                                    cacheManager.saveChargeSocketSlot(socketSlot);
                                }
                            }

                            //记录卡槽瞬时信息
                            CDCZSlotInstantLog instantLog = new CDCZSlotInstantLog();
                            instantLog.setIotId(iotClient.getIOTNote().getId());
                            instantLog.setDeviceSn(heartbeatNotify.getDeviceSn());
                            instantLog.setSlotNum(plugInfo.getSlotNum());
                            instantLog.setOverloadState(plugInfo.getOverloadState());
                            instantLog.setPowerState(plugInfo.getPowerState());
                            instantLog.setTemperatureState(plugInfo.getTemperatureState());
                            instantLog.setInstantPower(plugInfo.getNowPower());
                            instantLog.setInstantCurrent(plugInfo.getNowCurrent());
                            instantLog.setCreateDate(new Date());
                            iotLogServer.send(instantLog);

                            if (ECDCZPlugWorkState.Charge.index().equals(plugInfo.getWorkState())) {
                                if (StringTools.isBlank(socketSlot.getCurrentTradeNo())) {
                                    CDCZOrder cdczOrder = CDCZOrderService.self(new Date()).getNewWorkingByDevice(socketSlot.getDeviceSn(),socketSlot.getSlotNum());
                                    if(cdczOrder != null){
                                        ChargeSocketSlot temp = ChargeSocketSlotService.self().getByKeys(heartbeatNotify.getDeviceSn(), socketSlot.getSlotNum());
                                        if (StringTools.isBlank(temp.getCurrentTradeNo()) || !temp.getCurrentTradeNo().equals(cdczOrder.getTradeNo())) {
                                            ChargeSocketSlotService.self().toWorking(heartbeatNotify.getDeviceSn(),socketSlot.getSlotNum(),cdczOrder.getTradeNo());
                                        }
                                        socketSlot.setCurrentTradeNo(cdczOrder.getTradeNo());
                                        cacheManager.saveChargeSocketSlot(socketSlot);
                                    }
                                }
                                if (StringTools.isNotBlank(socketSlot.getCurrentTradeNo())) {
                                    int result = businessEventListener.chargeCheck(socketSlot.getCurrentTradeNo(), plugInfo.getNowPower(), plugInfo.getNowCurrent()
                                            , plugInfo.getElectricity(), plugInfo.getChargedTime(), operateInfo);
                                    if (result == 1) {
                                        if (networkService != null) {
                                            CDCZExecuteResult executeResult = networkService.closeCharge(heartbeatNotify.getDeviceSn(), socketSlot.getSlotNum());
                                            //TODO 执行结果判断
                                            log.info("设备开启成功，修改设备订单状态失败，订单号：{{0}}，关闭充电返回：{{1:json}}", socketSlot.getCurrentTradeNo(),executeResult);
                                        } else {
                                            log.error("充满即停检查，未获取充电插座IOT服务，卡槽信息：{{0:json}}", socketSlot);
                                        }
                                    }
                                }
                            }
                        } else {
                            if (ChargeSocketSlotEnum.State.Working.index().equals(socketSlot.getState())) {
                                log.error("{{0}}设备{{1}}卡槽状态为工作中，但心跳无该卡槽，修改卡槽为空闲",socketSlot.getDeviceSn(),socketSlot.getSlotNum());
                                if (ChargeSocketSlotService.self().toFree(socketSlot.getDeviceSn(), socketSlot.getSlotNum()) && toSave) {
                                    socketSlot.setState(ChargeSocketSlotEnum.State.Free.index());
                                    cacheManager.saveChargeSocketSlot(socketSlot);
                                }
                            }
                        }
                    } else {
                        log.error("设备心跳通知，未找到设备卡槽信息，设备序列号：{{0}}，卡槽号：{{1}}", heartbeatNotify.getDeviceSn(),slotNum);
                    }
                }
            }else {
                log.error("设备心跳通知，未找到设备信息，报文：{{0:json}}",heartbeatNotify);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            JdbcSession.clear();
            MultiDBTools.removeJdbcKey();
        }
    }

    @Override
    public void searchResult(IOTClient iotClient,CDCZSearchResultNotify searchResultNotify) {
        MultiDBTools.setJdbcKey(jdbcKey);
        try {
            //不使用缓存，强制更新
            ChargeSocket chargeSocket = ChargeSocketService.self().getByDeviceSn(searchResultNotify.getDeviceSn());
            if (chargeSocket != null) {
                ChargeSocketService.self().heartbeat(chargeSocket,null,null);
                chargeSocket.setState(ChargeSocketEnum.State.Online.index());
                chargeSocket.setHeartbeatData(new Date());
                cacheManager.saveChargeSocket(chargeSocket);
            }

            if (chargeSocket != null) {
                for (Integer slotNum = 1; slotNum <= chargeSocket.getSlotTotal(); slotNum++) {
                    CDCZPlugInfo plugInfo = null;
                    if (searchResultNotify.getPlugInfoList() != null && searchResultNotify.getPlugInfoList().size() > 0) {
                        for (CDCZPlugInfo item : searchResultNotify.getPlugInfoList()) {
                            if (item.getSlotNum().equals(slotNum)) {
                                plugInfo = item;
                                break;
                            }
                        }
                    }
                    ChargeSocketSlot socketSlot = ChargeSocketSlotService.self().getJoinByKeys(searchResultNotify.getDeviceSn(), slotNum);
                    if (socketSlot != null) {
                        if (plugInfo != null) {
                            ChargeSocketSlotService.self().updateInfo(socketSlot,
                                    plugInfo.getWorkState(), plugInfo.getOverloadState(), plugInfo.getPowerState(), plugInfo.getTemperatureState());
                            socketSlot.setOverloadState(plugInfo.getOverloadState());
                            socketSlot.setPowerState(plugInfo.getPowerState());
                            socketSlot.setTemperatureState(plugInfo.getTemperatureState());
                            if (ECDCZPlugWorkState.Charge.index().equals(plugInfo.getWorkState())) {
                                socketSlot.setState(ChargeSocketSlotEnum.State.Working.index());
                            } else {
                                socketSlot.setState(ChargeSocketSlotEnum.State.Free.index());
                            }
                        } else {
                            if (ChargeSocketSlotEnum.State.Working.index().equals(socketSlot.getState())) {
                                log.error("{{0}}设备{{1}}卡槽状态为工作中，但查询结果无该卡槽，修改卡槽为空闲",socketSlot.getDeviceSn(),socketSlot.getSlotNum());
                                ChargeSocketSlotService.self().toFree(socketSlot.getDeviceSn(), socketSlot.getSlotNum());
                            }
                            socketSlot.setState(ChargeSocketSlotEnum.State.Free.index());
                        }
                        cacheManager.saveChargeSocketSlot(socketSlot);
                    }

                    if (socketSlot != null) {
                        if (plugInfo != null) {
                            //记录卡槽瞬时信息
                            CDCZSlotInstantLog instantLog = new CDCZSlotInstantLog();
                            instantLog.setIotId(iotClient.getIOTNote().getId());
                            instantLog.setDeviceSn(searchResultNotify.getDeviceSn());
                            instantLog.setSlotNum(plugInfo.getSlotNum());
                            instantLog.setOverloadState(plugInfo.getOverloadState());
                            instantLog.setPowerState(plugInfo.getPowerState());
                            instantLog.setTemperatureState(plugInfo.getTemperatureState());
                            instantLog.setInstantPower(plugInfo.getNowPower());
                            instantLog.setInstantCurrent(plugInfo.getNowCurrent());
                            instantLog.setCreateDate(new Date());
                            iotLogServer.send(instantLog);
                        } else {
                            log.error("设备查询通知，未返回相应的卡槽信息，设备序列号：{{0}}，卡槽号：{{1}}", searchResultNotify.getDeviceSn(), slotNum);
                        }
                    } else {
                        log.error("设备查询通知，未找到设备卡槽信息，设备序列号：{{0}}，卡槽号：{{1}}", searchResultNotify.getDeviceSn(), slotNum);
                    }
                }
            } else {
                log.error("设备查询通知，未找到设备信息，报文：{{0:json}}", searchResultNotify);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            JdbcSession.clear();
            MultiDBTools.removeJdbcKey();
        }
    }

    @Override
    public void chargeStartupResult(IOTClient iotClient,CDCZChargeStartupResultNotify chargeStartupResultNotify) {
        MultiDBTools.setJdbcKey(jdbcKey);
        try {
            if (CDCZExecuteResult.SUCCESS.equals(chargeStartupResultNotify.getResultCode())){
                CDCZOrder useOrder = null;
                CDCZWorkCacheManager.DeviceWorkInfo deviceWorkInfo = CDCZWorkCacheManager.self().getData(chargeStartupResultNotify.getDeviceSn(),
                        chargeStartupResultNotify.getMessageId());
                if(deviceWorkInfo != null) {
                    useOrder = CDCZOrderService.self(new Date()).getByTradeNo(deviceWorkInfo.getTradeNo());
                }else{
                    useOrder = CDCZOrderService.self(new Date()).getNewOpeningByDevice(chargeStartupResultNotify.getDeviceSn(),chargeStartupResultNotify.getSlotNum());
                    if(useOrder != null) {
                        if (CDCZOrderEnum.State.Opening.index().equals(useOrder.getState())) {
                            Long minute = DateTools.differenceMinute(useOrder.getCreateDate(), new Date());
                            if (minute > 10) {  //大于10分钟，失效
                                log.error("设备充电开启成功，从数据库查询设备订单过期，订单号：{{0}}，过期时长：{{1}}分钟", useOrder.getTradeNo(), minute);
                                return;
                            }
                        }
                    }
                }

                ICDCZNetworkService networkService = getNetworkService(iotClient);
                if(useOrder != null) {
                    if(CDCZOrderEnum.State.Opening.index().equals(useOrder.getState())) {
                        if (CDCZOrderService.self(useOrder.getCreateDate()).openingToWorking(useOrder)) {
                            businessEventListener.chargeStart(useOrder);
                        }else{
                            log.error("设备开启成功，修改设备订单状态失败，订单号：{{0}}", useOrder.getTradeNo());
                            networkService.closeCharge(useOrder.getChargeSocketSn(), useOrder.getSlotNum());
                        }
                    }else if(!CDCZOrderEnum.State.Working.index().equals(useOrder.getState())){
                        log.error("设备开启成功，设备订单状态不正常，订单号：{{0}}，状态：{{1}}", useOrder.getTradeNo(),useOrder.getState());
                        networkService.closeCharge(useOrder.getChargeSocketSn(), useOrder.getSlotNum());
                    }
                }else{
                    log.error("设备充电开启成功，但未找到设备订单，通知内容：{{0:json}}",chargeStartupResultNotify);
                }
            }else{
                CDCZOrder useOrder = null;
                CDCZWorkCacheManager.DeviceWorkInfo deviceWorkInfo = CDCZWorkCacheManager.self().getData(chargeStartupResultNotify.getDeviceSn(),
                        chargeStartupResultNotify.getMessageId());
                if(deviceWorkInfo != null) {
                    useOrder = CDCZOrderService.self(new Date()).getByTradeNo(deviceWorkInfo.getTradeNo());
                }else{
                    useOrder = CDCZOrderService.self(new Date()).getNewOpeningByDevice(chargeStartupResultNotify.getDeviceSn(),chargeStartupResultNotify.getSlotNum());
                    if(useOrder != null) {
                        if (CDCZOrderEnum.State.Close.index().equals(useOrder.getState()) || CDCZOrderEnum.State.Finish.index().equals(useOrder.getState())
                                || CDCZOrderEnum.State.Fail.index().equals(useOrder.getState())) {
                            return;
                        }
                    }
                }

                if(useOrder != null) {
                    CDCZOrderService.self(useOrder.getCreateDate()).openingFail(useOrder, operateInfo);
                }else{
                    log.error("设备充电开启失败，但未找到设备订单，通知内容：{{0:json}}",chargeStartupResultNotify);
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }finally {
            JdbcSession.clear();
            MultiDBTools.removeJdbcKey();
        }
    }

    @Override
    public void chargeClose(CDCZChargeCloseNotify chargeCloseNotify) {
        log.info("获取设备充电结束通知，内容：{{0:json}}", chargeCloseNotify);
        MultiDBTools.setJdbcKey(jdbcKey);
        try {
            //关闭设备
            if(!ChargeSocketSlotService.self().toFree(chargeCloseNotify.getDeviceSn(),chargeCloseNotify.getSlotNum())){
                log.error("修改{{0}}充电插座{{1}}号插座状态为空闲时失败",chargeCloseNotify.getDeviceSn(),chargeCloseNotify.getSlotNum());
            }

            ChargeSocketSlot socketSlot = cacheManager.getChargeSocketSlot(chargeCloseNotify.getDeviceSn(), chargeCloseNotify.getSlotNum());
            if (socketSlot == null) {
                socketSlot = ChargeSocketSlotService.self().getJoinByKeys(chargeCloseNotify.getDeviceSn(), chargeCloseNotify.getSlotNum());
                if (socketSlot != null) {
                    cacheManager.saveChargeSocketSlot(socketSlot);
                }
            }else {
                //更新缓存
                socketSlot.setState(ChargeSocketSlotEnum.State.Free.index());
                cacheManager.saveChargeSocketSlot(socketSlot);
            }

            if (socketSlot != null) {
                //处理订单
                if (StringTools.isNotBlank(socketSlot.getCurrentTradeNo())) {
                    CDCZOrder useOrder = CDCZOrderService.self(new Date()).getByTradeNo(socketSlot.getCurrentTradeNo());
                    if (useOrder != null) {
                        if (CDCZOrderEnum.State.Working.index().equals(useOrder.getState())) {
                            businessEventListener.finishCharge(useOrder,chargeCloseNotify,operateInfo);
                        }
                        return;
                    }
                }else {
                    log.error("{{0}}充电插座{{1}}口返回充电完成，缓存无数据，触发设备卡槽订单排序获取最新订单检查", chargeCloseNotify.getDeviceSn()
                            , chargeCloseNotify.getSlotNum());
                }
            } else {
                log.error("{{0}}充电插座{{1}}口返回充电完成，但未找设备卡槽信息", chargeCloseNotify.getDeviceSn(), chargeCloseNotify.getSlotNum());
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            JdbcSession.clear();
            MultiDBTools.removeJdbcKey();
        }
    }

    @Override
    public void slotAbnormal(CDCZPlugAbnormalNotify abnormalNotify) {
        log.info("获取设备卡槽异常通知，内容：{{0:json}}",abnormalNotify);
    }

    @Override
    public void findSlaveDevice(CDCZFindSlaveDeviceResultNotify findSlaveDeviceResultNotify) {
        if(StringTools.isNotBlank(findSlaveDeviceResultNotify.getSlaveDeviceSn())) {
            ChargeSocketSlaveDevice socketSlaveDevice = ChargeSocketSlaveDeviceService.self().getByDeviceSn(findSlaveDeviceResultNotify.getSlaveDeviceSn());
            if (socketSlaveDevice != null) {
                if (ChargeSocketSlaveDeviceEnum.State.BindFinish.index().equals(socketSlaveDevice.getState())) {
                    //检查一下主机和绑定是否一致
                    if (!socketSlaveDevice.getMainDeviceSn().equals(findSlaveDeviceResultNotify.getDeviceSn())
                            || !socketSlaveDevice.getBindIndex().equals(findSlaveDeviceResultNotify.getBindIndex())) {
                        //不一致进行修改
                        if (!ChargeSocketSlaveDeviceService.self().faceSaveMainDeviceSnAndBindIndex(socketSlaveDevice.getDeviceSn()
                                , findSlaveDeviceResultNotify.getDeviceSn(), findSlaveDeviceResultNotify.getBindIndex(), null)) {
                            log.error("修改充电插座从机绑定主机信息失败，内容：{{0:json}}", findSlaveDeviceResultNotify);
                        }
                    }
                    return;
                }
            }

            if (!ChargeSocketSlaveDeviceService.self().faceSaveMainDeviceSnAndBindIndex(findSlaveDeviceResultNotify.getSlaveDeviceSn()
                    , findSlaveDeviceResultNotify.getDeviceSn(), findSlaveDeviceResultNotify.getBindIndex()
                    , ChargeSocketSlaveDeviceEnum.State.BindFinish.index())) {
                log.error("修改充电插座从机绑定主机信息失败，内容：{{0:json}}", findSlaveDeviceResultNotify);
            }
        }else{
            if (!ChargeSocketSlaveDeviceService.self().removeSlaveDevice(findSlaveDeviceResultNotify.getDeviceSn()
                    , findSlaveDeviceResultNotify.getBindIndex())) {
                log.error("修改充电插座从机绑定主机信息失败，内容：{{0:json}}", findSlaveDeviceResultNotify);
            }
        }
    }

    @Override
    public void bindSlaveDevice(CDCZBindSlaveDeviceNotify bindSlaveDeviceNotify) {
        ChargeSocketSlaveDevice socketSlaveDevice = ChargeSocketSlaveDeviceService.self()
                .getByMainDeviceSnAndBindIndex(bindSlaveDeviceNotify.getDeviceSn(),bindSlaveDeviceNotify.getBindIndex());
        if(socketSlaveDevice != null && ChargeSocketSlaveDeviceEnum.State.Binding.index().equals(socketSlaveDevice.getState())){
            ChargeSocketSlaveDeviceService.self().bindResult(socketSlaveDevice.getDeviceSn(),true);
        }
    }

    @Override
    public void removeSlaveDevice(CDCZRemoveSlaveDeviceNotify removeSlaveDeviceNotify) {
        ChargeSocketSlaveDeviceService.self().removeResult(removeSlaveDeviceNotify.getDeviceSn());
    }

    @Override
    public void restartResult(CDCZRestartResultNotify restartResultNotify) {
        log.info("获取设备重启通知，内容：{{0:json}}",restartResultNotify);
        MultiDBTools.setJdbcKey(jdbcKey);
        try {
            if(1 == restartResultNotify.getResultCode()){
                ChargeSocketService.self().offline(restartResultNotify.getDeviceSn());
                cacheManager.removeChargeSocket(restartResultNotify.getDeviceSn());
                cacheManager.removeChargeSocketSlot(restartResultNotify.getDeviceSn());
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }finally {
            JdbcSession.clear();
            MultiDBTools.removeJdbcKey();
        }
    }

    @Override
    public void upgrade(IOTClient iotClient,CDCZUpgradeNotify upgradeNotify) {
        log.info("获取设备升级通知，内容：{{0:json}}", upgradeNotify);
        MultiDBTools.setJdbcKey(jdbcKey);
        try {
            if (upgradeNotify.getType() == 1) {
                DeviceUpgradeTask upgradeTask = DeviceUpgradeTaskService.self().getUpgradingByDeviceSn(upgradeNotify.getDeviceSn());
                if(upgradeTask != null) {
                    UpgradeProcessInfo.Item item = null;
                    if (upgradeNotify.getState() == 1) {
                        item = new UpgradeProcessInfo.Item();
                        item.setDate(new Date());
                        item.setNote("固件开始升级");
                    }else {
                        item = new UpgradeProcessInfo.Item();
                        item.setDate(new Date());
                        item.setNote("固件升级，校验失败");
                    }

                    UpgradeProcessInfo processInfo = null;
                    if(JsonTools.isJsonStr(upgradeTask.getUpgradeProcessInfo())){
                        processInfo = JsonTools.fromJson(upgradeTask.getUpgradeProcessInfo(),UpgradeProcessInfo.class);
                    }else{
                        processInfo = new UpgradeProcessInfo();
                    }

                    processInfo.getItems().add(item);
                    DeviceUpgradeTaskService.self().updateProcessInfo(upgradeTask.getId(),processInfo);
                }else{
                    log.error("{{0}}设备未找到升级任务",upgradeNotify.getDeviceSn());
                }
            } else if (upgradeNotify.getType() == 2) {
                DeviceUpgradeTask upgradeTask = DeviceUpgradeTaskService.self().getUpgradingByDeviceSn(upgradeNotify.getDeviceSn());
                if(upgradeTask != null) {
                    UpgradeProcessInfo.Item item = null;
                    boolean flag = false;
                    if (upgradeNotify.getState() == 1) {
                        item = new UpgradeProcessInfo.Item();
                        item.setDate(new Date());
                        item.setNote("固件下载成功");
                        flag = true;
                    } else if (upgradeNotify.getState() == 2) {
                        item = new UpgradeProcessInfo.Item();
                        item.setDate(new Date());
                        item.setNote("再次确定固件下载成功");
                        flag = true;
                    } else {
                        item = new UpgradeProcessInfo.Item();
                        item.setDate(new Date());
                        item.setNote("固件下载失败");
                    }

                    if (flag) {
                        ICDCZNetworkService networkService = getNetworkService(iotClient);
                        if (networkService != null) {
                            networkService.upgrade(upgradeTask.getDeviceSn(),upgradeTask.getPackagePath(),upgradeTask.getPackageCRC());
                        }else{
                            log.error("未找到充电插座网络服务，设备序列号：{{0}}",upgradeTask.getDeviceSn());
                        }
                    }else{
                        DeviceUpgradeTaskService.self().toFail(upgradeTask.getId(),item.getNote());
                    }

                    UpgradeProcessInfo processInfo = null;
                    if(JsonTools.isJsonStr(upgradeTask.getUpgradeProcessInfo())){
                        processInfo = JsonTools.fromJson(upgradeTask.getUpgradeProcessInfo(),UpgradeProcessInfo.class);
                    }else{
                        processInfo = new UpgradeProcessInfo();
                    }

                    processInfo.getItems().add(item);
                    DeviceUpgradeTaskService.self().updateProcessInfo(upgradeTask.getId(),processInfo);
                }else{
                    log.error("{{0}}设备未找到升级任务",upgradeNotify.getDeviceSn());
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            JdbcSession.clear();
            MultiDBTools.removeJdbcKey();
        }
    }

    private ICDCZNetworkService getNetworkService(IOTClient iotClient){
        ICDCZNetworkService networkService = null;
        if (CDCZConstants.ProtocolTypeV1.equals(iotClient.getIOTNote().getProtocolType())) {
            networkService = new V1_CDCZNetworkService(iotClient);
        }else if (CDCZConstants.ProtocolTypeV2.equals(iotClient.getIOTNote().getProtocolType())) {
            networkService = new V2_CDCZNetworkService(iotClient);
        }
        return networkService;
    }
}
